package newtifyme.server;


import java.io.IOException;
import java.net.URL;
import java.util.Timer;
import java.util.TimerTask;

import com.google.gdata.client.youtube.YouTubeQuery;
import com.google.gdata.client.youtube.YouTubeService;
import com.google.gdata.data.DateTime;
import com.google.gdata.data.youtube.VideoEntry;
import com.google.gdata.data.youtube.VideoFeed;
import com.google.gdata.data.youtube.YouTubeMediaGroup;
import com.google.gdata.data.youtube.YtPublicationState;
import com.google.gdata.util.ServiceException;
import com.sun.net.httpserver.HttpExchange;


public	class SearchTimer {
  	    public final Timer timer = new Timer();
  	    private final int minutes;
  	    private String keyword;
  	    private String uuid;
  	    private String lastSearch;
  	    private DateTime lastDate;
  	    private String key = "AI39si44RG2PRFgMUncXsepdm6wiGQRWLlW4EzeZwmAlc1kclp6LP_yhzRE0qC_cI1egp0sgopFHmibcgtOo8146f4fxoqNiJA";
  	    YouTubeService service = new YouTubeService("local",key);
  	    private VideoEntry lastEntry;
  	    private boolean firstSearch;
  	    private boolean last;
  	    private DateTime tempDate;
  	    private HttpExchange exchange;
  	    public SearchTimer(int minutes, String keyword, String uid) {
  	        this.minutes = minutes;
  	        this.keyword = keyword;
  	        this.uuid =  uid;
  	        //this.lastDate=DateTime.parseDateTime("2011-04-13T02:27:57.000Z");
  	      this.lastDate=DateTime.now();
  	        this.lastEntry = null; 
  	        this.firstSearch = true;
  	        this.last = true;
  	    }

  	    public void start() {
  	        timer.schedule(new TimerTask() {
  	            public void run() {
  	                try {
						playSound();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (ServiceException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
  	                
  	                //timer.cancel();
  	            }
  	            private void playSound() throws IOException, ServiceException {
  	            	//lastDate = DateTime.now();
  	            	queryYouTube();
  	            	if (!last) lastDate = tempDate;
  	            	last = true;
  	                System.out.println("user: " + uuid + " keyword: " + keyword + " every " + minutes + "seconds");
  	                System.out.println("Query Time: " + DateTime.now() + " comparing with " + lastDate.toString());
  	                System.out.println("Query from " + exchange.getRemoteAddress().toString());
  	                // Start a new thread to play a sound...
  	            }
  	            private void queryYouTube() throws IOException, ServiceException {
  	            	YouTubeQuery query = new YouTubeQuery(new URL("http://gdata.youtube.com/feeds/api/videos"));
  	            	// order results by the number of views (most viewed first)
	  	      		query.setOrderBy(YouTubeQuery.OrderBy.UPDATED);
	  	      		query.setTime(YouTubeQuery.Time.TODAY);
	  	      		
	  	      		
	  	      		
	  	      		// search for puppies and include restricted content in the search results
	  	      		query.setFullTextQuery(keyword);
	  	      		query.setSafeSearch(YouTubeQuery.SafeSearch.NONE);
	
	  	      		VideoFeed videoFeed = service.query(query, VideoFeed.class);
	  	      		findLatestVideos(videoFeed,true);
	  	      		//printVideoFeed(videoFeed, true);
  	            }
  	            private void findLatestVideos(VideoFeed videoFeed, boolean detailed) {
  	            	for(VideoEntry videoEntry : videoFeed.getEntries() ) {
  	            		printLast(videoEntry, detailed);
  	            	}
  	            }
  	            	public  void printLast(VideoEntry videoEntry, boolean detailed) {
  	            	  

  	            	  if(videoEntry.isDraft()) {
  	            	    System.out.println("Video is not live");
  	            	    YtPublicationState pubState = videoEntry.getPublicationState();
  	            	    if(pubState.getState() == YtPublicationState.State.PROCESSING) {
  	            	      System.out.println("Video is still being processed.");
  	            	    }
  	            	    else if(pubState.getState() == YtPublicationState.State.REJECTED) {
  	            	      System.out.print("Video has been rejected because: ");
  	            	      System.out.println(pubState.getDescription());
  	            	      System.out.print("For help visit: ");
  	            	      System.out.println(pubState.getHelpUrl());
  	            	    }
  	            	    else if(pubState.getState() == YtPublicationState.State.FAILED) {
  	            	      System.out.print("Video failed uploading because: ");
  	            	      System.out.println(pubState.getDescription());
  	            	      System.out.print("For help visit: ");
  	            	      System.out.println(pubState.getHelpUrl());
  	            	    }
  	            	  }

  	            	  if(videoEntry.getEditLink() != null) {
  	            	    System.out.println("Video is editable by current user.");
  	            	  }

  	            	  if(detailed) {
  	            		  
  	            	    YouTubeMediaGroup mediaGroup = videoEntry.getMediaGroup();
  	            	    if (compareDates(lastDate.toString(), mediaGroup.getUploaded().toString())) {
  	            	    	if(last) {
  	            	    		lastEntry = videoEntry;
  	            	    		last = false;
  	            	    		tempDate = videoEntry.getUpdated();
  	            	    		System.out.println("Last QueryTime: " + lastDate.toString() +" changed to " + tempDate.toString());
  	            	    		System.out.println("Query from " + exchange.getRemoteAddress().toString());
  	            	    	}
  	            	    	
  	            	    	System.out.println("Title: " + videoEntry.getTitle().getPlainText());
  	            	    	String m = videoEntry.getHtmlLink().getHref();
//  	            	    	System.out.println(m);
//  	            	    	System.out.println(m.split("=")[1].split("&")[0]);
  	            	    	String vid = m.split("=")[1].split("&")[0];
  	            	    	String title = videoEntry.getTitle().getPlainText();
  	            	    	System.out.println( mediaGroup.getUploaded().toString());
  	            	    	String str = "uid=1&init&puppy&1";
  	            			HTTPRequestPoster hp = new HTTPRequestPoster();
  	            			hp.sendGetRequest("http://192.168.1.15:6789/init", "!"+keyword+"!"+title+"!"+vid);
  	            	    }
  	            	  }
  	            	  
  	            	}
  	            	/**
  	            	 * checks if data1 is older than date2
  	            	 * @param date1
  	            	 * @param date2
  	            	 */
  	            	public boolean compareDates(String date1, String date2) {
  	            		//compare year
  	            		//System.out.println("Comparing " + date1 + " to " + date2);
  	            		int year1 = Integer.parseInt(date1.split("-")[0]);
  	            		int year2 = Integer.parseInt(date2.split("-")[0]);
  	            		if(date1.equals(date2)) return false;
  	            		if (year1 > year2)
  	            			return false;
  	            		else {
  	            			int month1 = Integer.parseInt(date1.split("-")[1]);
  	            			int month2 = Integer.parseInt(date2.split("-")[1]);
  	            			if (month1 > month2)
  	            				return false;
  	            			else {
  	            				int datee1 = Integer.parseInt(date1.split("-")[2].split("T")[0]);
  	            				int datee2 = Integer.parseInt(date2.split("-")[2].split("T")[0]);
  	            				if (datee1>datee2)
  	            					return false;
  	            				else {
  	            					date1 = date1.split("T")[1];
  	            					date2 = date2.split("T")[1];
  	            					
  	            					int hour1 = Integer.parseInt(date1.split(":")[0]);
  	            					//System.out.println(hour1);
  	            					
  	            					int hour2 = Integer.parseInt(date2.split(":")[0]);
  	            					
  	            					if ( hour1> hour2) return false;
  	            					else if (hour1< hour2) return true;
  	            					else {
  	            						//System.out.println(hour2);
  	            						int min1= Integer.parseInt(date1.split(":")[1]);
  	            						int min2= Integer.parseInt(date2.split(":")[1]);
  	            						if (min1>min2) {
  	            							return false;
  	            						} else {
  	            							return true;
  	            						}
  	            					}
  	            				}
  	            			}
  	            		}
  	            			
  	            	}
  	            	
  	            	
  	            	
  	  	
  	            
  	            
  	        }, 0, minutes*60* 1000);
  	    }

		public void put(HttpExchange exchange) {
			this.exchange = exchange;
		}

  	  
  	}